package com.plugin.uniapp;

import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.plugin.uniapp.dialog.MultiViewDialog;
import com.plugin.uniapp.utils.HttpHelper;
import com.plugin.uniapp.utils.Logger;
import com.plugin.uniapp.video.SurfacePlayer;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    public static MainActivity instance;
    public TextureAdapter textureAdapter;
    public boolean hasSomeonePopup = false;
    public Map<String, List<Task>> deviceExtraTasks = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity);
        setWhiteStatusBar();
        instance = this;

        findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        String apiUrl = Config.APIBaseUrl + Config.APIGetDevices + "?islogin=" + Config.IsLogin;
        log("请求设备列表：" + apiUrl);
        HttpHelper.getAsync(apiUrl, new HttpHelper.Callback() {
            @Override
            public void onSuccess(String response) {
                log("请求设备列表成功：" + response);
                try {
                    JSONObject json = new JSONObject(response);
                    if (json.getInt("code") != 200) {
                        error(json.getString("message"));
                        return;
                    }
                    JSONObject data = json.getJSONObject("data");
                    Config.lockedDeviceId = data.getString("locked_device");
                    createPlayers(data.getJSONArray("devices"));
                } catch (JSONException e) {
                    error(e.toString());
                }
            }
        });
    }

    private void createPlayers(JSONArray devices) {
        List<String> deviceIds = new ArrayList<>();
        log("获取设备数量：" + devices.length());
        final boolean haveLockedDevice = Config.lockedDeviceId != null && !Config.lockedDeviceId.isEmpty();
        try {
            for (int i = 0; i < devices.length(); i++) {
                if (haveLockedDevice) {
                    if (!devices.getString(i).equals(Config.lockedDeviceId)) {
                        deviceIds.add(devices.getString(i));
                    }
                } else {
                    deviceIds.add(devices.getString(i));
                }
            }
            if (haveLockedDevice) {
                deviceIds.add(0, Config.lockedDeviceId);
            }
        } catch (JSONException e) {
            error(e.toString());
        }

        if (Config.TestDeviceId != null && !Config.TestDeviceId.isEmpty()) {
            log("但使用测试设备：" + Config.TestDeviceId);
            //deviceIds.clear();
            deviceIds.add(0, Config.TestDeviceId);
            Config.lockedDeviceId = Config.TestDeviceId;
        }

        if (deviceIds.isEmpty()) {
            findViewById(R.id.empty_tip).setVisibility(View.VISIBLE);
            findViewById(R.id.recycler_view).setVisibility(View.GONE);
        } else {
            findViewById(R.id.empty_tip).setVisibility(View.GONE);
            findViewById(R.id.recycler_view).setVisibility(View.VISIBLE);
        }

        // 设置RecyclerView
        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new GridLayoutManager(this, Config.Col));
        textureAdapter = new TextureAdapter(deviceIds);
        recyclerView.setAdapter(textureAdapter);
    }

    private void setWhiteStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // Android 6.0+ 设置浅色状态栏
            View decor = getWindow().getDecorView();
            int flags = decor.getSystemUiVisibility();
            flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; // 设置状态栏文字/图标为暗色
            decor.setSystemUiVisibility(flags);

            // 设置状态栏背景色为白色
            getWindow().setStatusBarColor(Color.WHITE);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // Android 5.0+ 只能设置状态栏背景色
            getWindow().setStatusBarColor(Color.WHITE);
            // 无法直接设置文字颜色，会保持白色文字
        }
    }

    public void openDialog(SurfacePlayer player, String deviceId) {
        hasSomeonePopup = true;
        textureAdapter.stopAllPlayers(deviceId);
        new MultiViewDialog(this, player, deviceId).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        log("onDestroy()");
        instance = null;
        if (textureAdapter != null) {
            textureAdapter.onDestroy();
        }
    }

    private void log(String msg) {
        Logger.log(msg, getClass(), false);
    }

    private void error(String msg) {
        Logger.error(msg, getClass(), false);
    }
}